package com.wf.it.hpwebplan.interceptor;

import com.alibaba.fastjson.JSON;
import com.wf.it.common.entity.User;
import com.wf.it.common.util.JsonUtil;
import com.wf.it.common.util.JwtUtil;
import com.wf.it.common.vo.Result;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwtstr=request.getHeader("jwt_token");
        if(jwtstr==null)
            return true;
        Claims claims =null;
        try {
            claims = JwtUtil.parseToken("112233", jwtstr);
        }catch (Exception ex){
          JsonUtil.outJson(response,new Result<>(401,null,"凭证无效"));
          return false;
        }
        Map<String,Object> map= (Map<String, Object>) claims.get("user");
        User user=new User();
        user.setId((Integer) map.get("id"));
        user.setName((String) map.get("name"));
        user.setLoginName((String) map.get("loginName"));
        user.setEmail((String) map.get("email"));
        user.setIdCard((String) map.get("idCard"));
        user.setPhone((String) map.get("phone"));
        user.setBalance(Float.parseFloat(map.get("balance").toString()));
        user.setState((Integer) map.get("state"));
        user.setRole((String) map.get("role"));
        user.setPhoto((String) map.get("photo"));
        user.setMap((Map<String, Object>) map.get("map"));
        request.setAttribute("cur_user",user);//放request作用域,传给后续的各个Controller使用
        System.out.println("解析成功user放到request快递柜");
        return true;
    }
}
